/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrmNode.java
 *
 * Created on Mar 25, 2009, 10:59:33 PM
 */
package org.grid.maingui;

import java.rmi.RemoteException;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.table.DefaultTableModel;
import org.grid.gui.MessageBox;
import org.grid.model.Node;
import org.grid.model.NodeManager;
import org.grid.model.rmi.LoadTest;
import org.grid.model.rmi.LogCalculator;

/**
 *
 * @author wellington
 */
public class JFrmNode extends javax.swing.JInternalFrame {

    // <editor-fold defaultstate="collapsed" desc="Singleton">
    private static JFrmNode instance;

    public static JFrmNode getInstance(JDesktopPane owner) {
        if (instance == null) {
            instance = new JFrmNode();
        }
        owner.add(instance);
        instance.setVisible(true);
        instance.refresh();
        owner.getDesktopManager().activateFrame(instance);
        return instance;
    }
    public static JFrmNode getInstance() {
        if (instance == null) {
            instance = new JFrmNode();
        }
        return instance;
    }
    /** Creates new form JFrmNode */
    public JFrmNode() {
        initComponents();
        nodeManager = new NodeManager();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Attributes">
    private NodeManager nodeManager;
    // </editor-fold>

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        pnlNodes = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblNodes = new javax.swing.JTable();
        pnlButtons = new javax.swing.JPanel();
        btnAdd = new javax.swing.JButton();
        btnAlter = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        btnTest = new javax.swing.JButton();
        lblLoad = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("NodeGUI");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/maingui/main.png"))); // NOI18N
        setVisible(true);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pnlNodes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pnlNodes.setLayout(new java.awt.GridBagLayout());

        tblNodes.setShowVerticalLines(false);
        jScrollPane1.setViewportView(tblNodes);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlNodes.add(jScrollPane1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
        getContentPane().add(pnlNodes, gridBagConstraints);

        pnlButtons.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/+.png"))); // NOI18N
        btnAdd.setText("Adicionar");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        pnlButtons.add(btnAdd);

        btnAlter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/edit.png"))); // NOI18N
        btnAlter.setText("Alterar");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tblNodes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement!=null}"), btnAlter, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        btnAlter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterActionPerformed(evt);
            }
        });
        pnlButtons.add(btnAlter);

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/-.png"))); // NOI18N
        btnRemove.setText("Remover");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, tblNodes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement!=null}"), btnRemove, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });
        pnlButtons.add(btnRemove);

        btnTest.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/refresh.png"))); // NOI18N
        btnTest.setText("Testar");
        btnTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestActionPerformed(evt);
            }
        });
        pnlButtons.add(btnTest);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(pnlButtons, gridBagConstraints);

        lblLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/grid/resources/loader.gif"))); // NOI18N
        lblLoad.setText("Carregando");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        getContentPane().add(lblLoad, gridBagConstraints);
        lblLoad.setVisible(false);

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-450)/2, (screenSize.height-350)/2, 450, 350);
    }// </editor-fold>//GEN-END:initComponents

    // <editor-fold defaultstate="collapsed" desc="Events">
    private void btnTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestActionPerformed
        testNodes();
}//GEN-LAST:event_btnTestActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        add();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnAlterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterActionPerformed
        edit();
    }//GEN-LAST:event_btnAlterActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        remove();
    }//GEN-LAST:event_btnRemoveActionPerformed
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Methods">
    private void refresh() {
        nodeManager.load();
        List<Node> nodes = nodeManager.list();
        String[] headers = new String[]{"Nó", "Endereço", "Situação", "Resposta (ms)"};
        String[][] data = new String[nodes.size()][headers.length];
        for (int i = 0; i < nodes.size(); i++) {
            data[i][0] = nodes.get(i).getDescription();
            data[i][1] = nodes.get(i).getAddress() + ":" + nodes.get(i).getPort();
            data[i][2] = "...";
            data[i][3] = "...";
        }
        tblNodes.setModel(new DefaultTableModel(data, headers));
    }

    private void testNodes() {
        Runnable r = new Runnable() {
            public void run() {
                test();
            }
        };
        Thread t = new Thread(r);
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();
    }

    private void test() {        
        btnTest.setEnabled(false);
        lblLoad.setVisible(true);
        List<Node> nodes = nodeManager.list();
        for (int i = 0; i < nodes.size(); i++) {
            tblNodes.getModel().setValueAt("Testando...", i, 2);
            LogCalculator lc = nodes.get(i).getLogCalculator(true);
            if (lc != null) {
                try {
                    tblNodes.getModel().setValueAt((lc.isWorking() ? "Ocupado" : "Disponível"), i, 2);
                    long response = lc.testResponseTime(LoadTest.DEFAULT_LOAD_TEST);
                    tblNodes.getModel().setValueAt(response, i, 3);
                } catch (RemoteException ex) {
                    tblNodes.getModel().setValueAt("Erro", i, 2);
                    tblNodes.getModel().setValueAt("Erro", i, 3);
                }
            } else {
                tblNodes.getModel().setValueAt("Indisponível", i, 2);
                tblNodes.getModel().setValueAt("...", i, 3);
            }
        }
        lblLoad.setVisible(false);
        btnTest.setEnabled(true);
    }

    private void add() {
        Node n = new JFrmNodeEdit(null, true).showDialog();
        if (n != null) {
            nodeManager.addNode(n);
            if (nodeManager.save()) {
                refresh();
            } else {
                MessageBox.showError(this, "Erro ao adicionar ");
            }

        }
    }

    private void edit() {
        Node n = new JFrmNodeEdit(null, true).showDialog(nodeManager.list().get(tblNodes.getSelectedRow()));
        if (n != null) {
            if (nodeManager.save()) {
                refresh();
            } else {
                MessageBox.showError(this, "Erro ao alterar ");
            }
        }

    }

    private void remove() {
        Node n = nodeManager.list().get(tblNodes.getSelectedRow());
        nodeManager.removeNode(n);
        if (nodeManager.save()) {
            refresh();
        } else {
            MessageBox.showError(this, "Erro ao excluir ");
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Components">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnAlter;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnTest;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblLoad;
    private javax.swing.JPanel pnlButtons;
    private javax.swing.JPanel pnlNodes;
    private javax.swing.JTable tblNodes;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>
}
